package com.faiz.algorithm;

public class DetectCycle {
    public ListNode detectCycle(ListNode head) {
        // 快慢指针
        ListNode slow = head, fast = head;

        while (fast != null && fast.next != null) {

            fast = fast.next.next;
            slow = slow.next;
            if (slow == fast) break;
        }
        // 不是环
        if (fast == null || fast.next == null) {
            return null;
        }
        // 查找入环的第一个节点

        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }

        return fast;
    }
}
